package com.jk.service;


import ch.qos.logback.core.pattern.FormatInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jk.dao.CartDao;
import com.jk.dao.OrderDao;
import com.jk.dao.ProductDao;
import com.jk.entity.*;
import com.jk.utils.PayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class CartService {

    @Autowired
    private CartDao cartDao;

    @Autowired
    private RedisTemplate redisTemplate;

     @Autowired
     private ProductDao productDao;

     @Autowired
     private OrderDao orderDao;
    public List<Cart> queryCartList(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        Gson gson = new Gson();
        HashOperations hashOperations = redisTemplate.opsForHash();
        String cart = (String) hashOperations.get("cart", user.getUser_id());
        List<Cart> list= gson.fromJson(cart, new TypeToken<List<Cart>>() {}.getType());
        return list;
    }

    public void addCart(HttpServletRequest request,String id,Integer num) {
        User user = (User) request.getSession().getAttribute("user");
        Gson gson = new Gson();
        Boolean has = redisTemplate.opsForHash().hasKey("cart",user.getUser_id());
        /*此处需要es查询商品信息*/
        Product product = cartDao.queryById(id);
        Cart cart = new Cart();
        cart.setProductId(product.getProduct_id());
        cart.setProductName(product.getProduct_name());
        cart.setProductPrice(product.getProduct_price());
        cart.setProductImage(product.getProduct_imgurl());
        cart.setUserId(user.getUser_id());
        cart.setNum(num);
        if (user!=null){
            if (has){
                boolean boo =false;
                int index=0;
                List<Cart> cartList = new ArrayList<Cart>();
                String cart1 = (String) redisTemplate.opsForHash().get("cart", cart.getUserId());
                cartList = gson.fromJson(cart1, new TypeToken<List<Cart>>() {}.getType());
                for (int i = 0; i < cartList.size(); i++) {
                    if (id.equals(cartList.get(i).getProductId())){
                        index=i;
                        boo=true;
                    }
                }
                if (boo){
                    cartList.get(index).setNum(cartList.get(index).getNum()+1);
                }else{
                    cartList.add(cart);
                }
                Map<String, Object> map = new HashMap<>();
                map.put(cart.getUserId(),gson.toJson(cartList));
                redisTemplate.opsForHash().putAll("cart",map);
            }else {
                List<Cart> list = new ArrayList<Cart>();
                list.add(cart);
                Map<String, Object> map = new HashMap<>();
                map.put(cart.getUserId(),gson.toJson(list));
                redisTemplate.opsForHash().putAll("cart",map);
                }
        }else{
            List<Cart> cartList = new ArrayList<Cart>();
            cartList.add(cart);
            request.getSession().setAttribute("cart",gson.toJson(cartList));
        }
    }
/*

    public void add(Cart cart) {
        Boolean has = redisTemplate.opsForHash().hasKey("cart",cart.getUserId());
        Gson gson = new Gson();
        if (has){
            List<Cart> listPro = new ArrayList<Cart>();
            String cart1 = (String) redisTemplate.opsForHash().get("cart", cart.getUserId());
            listPro = gson.fromJson(cart1, new TypeToken<List<Cart>>() {
            }.getType());
            listPro.add(cart);
            Map<String, Object> map = new HashMap<>();
            map.put(cart.getUserId(),gson.toJson(listPro));
            redisTemplate.opsForHash().putAll("cart",map);

        }else {
            List<Cart> list = new ArrayList<Cart>();
            list.add(cart);
            Map<String, Object> map = new HashMap<>();
            map.put(cart.getUserId(),gson.toJson(list));
            redisTemplate.opsForHash().putAll("cart",map);
        }
    }
*/

    public void del(HttpServletRequest request,String productId) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String cart = (String) redisTemplate.opsForHash().get("cart", user.getUser_id());
        List<Cart> cartList = new ArrayList<Cart>();
        Gson gson = new Gson();
        cartList = gson.fromJson(cart, new TypeToken<List<Cart>>() {}.getType());
        for (int i = 0; i <cartList.size() ; i++) {
            if(productId.equals(cartList.get(i).getProductId())){
                cartList.remove(i);
            }
        }
        redisTemplate.opsForHash().delete("cart",user.getUser_id());
        Map<String, Object> map = new HashMap<>();
        map.put(user.getUser_id(),gson.toJson(cartList));
        redisTemplate.opsForHash().putAll("cart",map);
    }

    public Product productNum(String productId) {
        Product product = cartDao.queryCount(productId);
        return product;
    }

    public void updNum(HttpServletRequest request, String productId, Integer num) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String cart = (String) redisTemplate.opsForHash().get("cart", user.getUser_id());
        List<Cart> cartList = new ArrayList<Cart>();
        Gson gson = new Gson();
        cartList = gson.fromJson(cart, new TypeToken<List<Cart>>() {}.getType());
        for (int i = 0; i <cartList.size() ; i++) {
            if(productId.equals(cartList.get(i).getProductId())){
                cartList.get(i).setNum(num);
                if (cartList.get(i).getNum()<=0){
                    cartList.remove(i);
                }
            }
        }
        redisTemplate.opsForHash().delete("cart",user.getUser_id());
        Map<String, Object> map = new HashMap<>();
        map.put(user.getUser_id(),gson.toJson(cartList));
        redisTemplate.opsForHash().putAll("cart",map);
    }

    public void submitOrder(HttpServletRequest request, String[] list, HttpServletResponse httpResponse, String couponId,String cname, String cphone, String address ) throws IOException {
        Consignee consignee = new Consignee();
        consignee.setConsignee_address(address);
        consignee.setConsignee_phone(cphone);
        consignee.setConsignee_name(cname);
        redisTemplate.opsForValue().set("consignne",consignee);


        User user= (User) request.getSession().getAttribute("user");
        Gson gson=new Gson();
        HashOperations hashOperations=redisTemplate.opsForHash();
        String cart= (String) hashOperations.get("cart",user.getUser_id());
        List<Cart> list2=gson.fromJson(cart,new TypeToken<List<Cart>>(){}.getType());
        String coupon= (String) hashOperations.get("coupon",user.getUser_id());
        List<Coupon> list3=gson.fromJson(coupon,new TypeToken<List<Coupon>>(){}.getType());
        String name="aa";
        String info="bb";
        Double count=0.0;
        for (int i = 0; i <list2.size() ; i++) {
            Cart cartByRedis=new Cart();
            cartByRedis=list2.get(i);
            for (int j = 0; j < list.length; j++) {
                if(cartByRedis.getProductId().toString().equals(list[j])){
                    count+=cartByRedis.getProductPrice()*cartByRedis.getNum();
                    name+=list2.get(i).getProductName();

                    String carId=cartByRedis.getProductId();

                    Product pro=productDao.getCarId(carId);
                    SimpleDateFormat sim1=new SimpleDateFormat("yyyyMMddHHmmssSS");
                    int floor =(int)Math.round(Math.random() * 899 + 100);

                    String id1 = sim1.format(new Date())+""+floor+""+user.getUser_id()+""+cartByRedis.getProductId();

                    Order order=new Order();
                    order.setOrder_id(id1);
                    order.setOrder_receiverinfo(pro.getProduct_description());

                    order.setUser_id(user.getUser_id());
                    order.setUser_name(user.getUser_nickname());
                    SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    order.setOrder_time(sim.format(new Date()));
                    order.setOrder_paystate(1);
                    order.setStateofpayment(1);
                    order.setConsignee_address(address);
                    order.setConsignee_phone(cphone);
                    order.setConsignee_name(cname);
                    OrderItem orderItem = new OrderItem();
                    orderItem.setNum(cartByRedis.getNum());

                    Double mon=   cartByRedis.getNum()*cartByRedis.getProductPrice();
                    order.setOrder_money(mon);
                    orderItem.setProduct_price(pro.getProduct_price());
                    orderItem.setOrder_id(id1);
                    orderItem.setProduct_id(pro.getProduct_id());
                    orderItem.setProduct_image(pro.getProduct_imgurl());
                    orderItem.setProduct_name(pro.getProduct_name());


                    OrderandItem orderandItem=new OrderandItem();
                    orderandItem.setOrder_id(order.getOrder_id());
                    orderandItem.setOrder_money(orderItem.getProduct_price());
                    orderandItem.setOrder_receiverinfo(pro.getProduct_description());
                    orderandItem.setUser_id(order.getUser_id());
                    orderandItem.setOrder_time(order.getOrder_time());
                    orderandItem.setOrder_paystate(order.getOrder_paystate());
                    orderandItem.setStateofpayment(order.getStateofpayment());
                    orderandItem.setConsignee_phone(order.getConsignee_phone());
                    orderandItem.setConsignee_name(order.getConsignee_name());
                    orderandItem.setConsignee_address(order.getConsignee_address());

                    orderandItem.setNum(1);
                    orderandItem.setProduct_price(orderItem.getProduct_price());
                    orderandItem.setOrder_id(order.getOrder_id());
                    orderandItem.setProduct_id(orderItem.getProduct_id());
                    orderandItem.setProduct_image(orderItem.getProduct_image());
                    orderandItem.setProduct_name(orderItem.getProduct_name());


                    List  list6 = new ArrayList();
                    list6.add(orderandItem);
                    Map<String, Object> map1 = new HashMap<>();
                    map1.put(user.getUser_id(),gson.toJson(list6));
                    redisTemplate.opsForHash().putAll("orderItme",map1);

                }
            }
        }
        System.out.println(count);
        Double couponJ=0.0;
        int index= 0;
        Double money= 0.0;
        if (!couponId.equals("0")){
            for (int i = 0; i < list3.size(); i++) {
                if (couponId.equals(list3.get(i).getCoupon_id())){
                    couponJ=list3.get(i).getCoupon_discount();
                    index=i;
                }
            }
            list3.remove(index);
            redisTemplate.opsForHash().delete("coupon",user.getUser_id());
            Map<String, Object> map2 = new HashMap<>();
            map2.put(user.getUser_id(),gson.toJson(list3));
            redisTemplate.opsForHash().putAll("coupon",map2);
        }
        if (count>couponJ){
            money=count-couponJ;
        }else {
            money=count;
        }
        PayUtils payUtils = new PayUtils();
        System.out.println(money);
        System.out.println(name);
        System.out.println(info);
        payUtils.alipay(httpResponse,money,name,info);

        //
        Map<String, Object> map = new HashMap<>();
        map.put(user.getUser_id(),gson.toJson(list));
        redisTemplate.opsForHash().putAll("order",map);
    }

    public void pay(HttpServletRequest request) {
        Gson gson = new Gson();
        User user = (User) request.getSession().getAttribute("user");
        String cart = (String) redisTemplate.opsForHash().get("cart", user.getUser_id());
        String order2 = (String) redisTemplate.opsForHash().get("order",user.getUser_id());
        Consignee consignne = (Consignee) redisTemplate.opsForValue().get("consignne");

        String order1 =(String) redisTemplate.opsForHash().get("orderItme", user.getUser_id());
        List<OrderandItem>  list1=gson.fromJson(order1, new TypeToken<List<OrderandItem>>() {}.getType());

        Order order=new Order();
        OrderItem orderItem = new OrderItem();






        List<Cart> list2 = gson.fromJson(cart, new TypeToken<List<Cart>>() {}.getType());
        String [] list = gson.fromJson(order2, new TypeToken<String []>() {}.getType());

        for (int i = 0; i <list2.size() ; i++) {
            Cart cartByRedis=new Cart();
            cartByRedis=list2.get(i);
            for (int j = 0; j < list.length; j++) {
                if(cartByRedis.getProductId().toString().equals(list[j])){
                    String carId=cartByRedis.getProductId();

                    for (int z = 0; z < list1.size(); z++) {

                        SimpleDateFormat sim1=new SimpleDateFormat("yyyyMMddHHmmssSS");
                        int floor =(int)Math.round(Math.random() * 899 + 100);
                        String id1 = sim1.format(new Date())+""+floor+""+user.getUser_id();

                        order.setOrder_id(id1);
                        order.setOrder_money(list1.get(z).getProduct_price());
                        order.setOrder_receiverinfo(list1.get(z).getOrder_receiverinfo());
                        order.setUser_id(list1.get(z).getUser_id());
                        order.setOrder_time(list1.get(z).getOrder_time());
                        order.setOrder_paystate(1);
                        order.setStateofpayment(1);
                        order.setConsignee_phone(list1.get(z).getConsignee_phone());
                        order.setConsignee_name(list1.get(z).getConsignee_name());
                        order.setConsignee_address(list1.get(z).getConsignee_address());

                        orderItem.setNum(list1.get(z).getNum());
                        orderItem.setProduct_price(list1.get(z).getProduct_price());
                        orderItem.setOrder_id(list1.get(z).getOrder_id());
                        orderItem.setProduct_id(list1.get(z).getProduct_id());
                        orderItem.setProduct_image(list1.get(z).getProduct_image());
                        orderItem.setProduct_name(list1.get(z).getProduct_name());
                        orderDao.addOrderItems(orderItem);
                        orderDao.addorder(order);
                    }

                }
            }
        }
        redisTemplate.opsForHash().delete("order",user.getUser_id());
        redisTemplate.opsForHash().delete("cart",user.getUser_id());
        for (int i = 0; i < list2.size(); i++) {
            for (int j = 0; j < list.length; j++) {
                if (list2.get(i).getProductId().equals(list[j])){
                    list2.remove(i);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put(user.getUser_id(),gson.toJson(list2));
        redisTemplate.opsForHash().putAll("cart",map);
    }
        

}

